<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <style>
        .layui-btn-warm {
            background-color: #FFB800;
            color: #fff;
        }
        .status-switch {
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <!-- 搜索表单 -->
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">用户姓名</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn">
                                <i class="layui-icon"></i> 搜 索
                            </button>
                            <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="resetSearchBtn">
                                <i class="layui-icon">ဂ</i> 重置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <!-- 工具栏 -->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm" lay-event="add">添加用户</button>
                <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="assign">分配角色</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">删除用户</button>
            </div>
        </script>

        <!-- 表格容器 -->
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="status">
            {{ d.state === '启用' ? '禁用' : '启用' }}
        </a>
        <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="viewRole">角色信息</a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>

        </script>


        <!-- 添加/编辑用户弹窗 -->
        <div id="userEdit" style="display: none; padding: 20px;">
            <form class="layui-form" lay-filter="userForm">
                <input type="hidden" name="userId">
                <div class="layui-form-item">
                    <label class="layui-form-label">账户</label>
                    <div class="layui-input-block">
                        <input type="text" name="account" required lay-verify="required" placeholder="请输入账户" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="userName" required lay-verify="required" placeholder="请输入真实姓名" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-block">
                        <input type="radio" name="gender" value="男" title="男">
                        <input type="radio" name="gender" value="女" title="女">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">电话</label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" required lay-verify="required" placeholder="请输入电话" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">住址</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" required lay-verify="required" placeholder="请输入住址" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">部门</label>
                    <div class="layui-input-block">
                        <select name="departmentId" id="departmentSelect" lay-verify="required">
                            <option value="">请选择部门</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="saveUser">保存</button>
                    </div>
                </div>
            </form>
        </div>
        <div id="roleAssign" style="display: none; padding: 20px;">
            <form class="layui-form" lay-filter="roleForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">选择角色</label>
                    <div class="layui-input-block">
                        <select name="roleId" id="roleSelect" lay-verify="required">
                            <option value="">请选择角色</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="saveRoleAssign">保存分配</button>
                    </div>
                </div>
            </form>
        </div>
        <!-- 新增角色信息弹窗 -->
        <!-- 角色信息弹窗 -->
        <div id="roleInfo" style="display: none; padding: 20px;">
            <table class="layui-table">
                <colgroup>
                    <col width="150">
                    <col width="100">
                    <col width="80">
                </colgroup>
                <thead>
                <tr>
                    <th>角色名称</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="roleInfoContent">
                <!-- 动态插入角色数据 -->
                </tbody>
            </table>
        </div>
    </div>
</div>
<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;

        // 加载部门数据
        function loadDepartments() {
            $.getJSON('/department/queryAll', function (res) {
                if (res.code === 0 && res.data) {
                    var options = '';
                    res.data.forEach(function (item) {
                        options += `<option value="${item.value}">${item.name}</option>`;
                    });
                    $("#departmentSelect").html('<option value="">请选择部门</option>' + options);
                    form.render('select');
                }
            });
        }

        // 初始化表格
        table.render({
            elem: '#currentTableId',
            url: '/user/queryPage',
            method: 'post',
            contentType: 'application/json',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'userId', width: 80, title: 'ID', sort: true},
                {field: 'account', width: 120, title: '账户'},
                {field: 'userName', width: 80, title: '姓名'},
                {field: 'gender', width: 80, title: '性别'},
                {field: 'phone', width: 120, title: '电话'},
                {field: 'depName', width: 100, title: '所属部门'},
                {field: 'state', width: 100, title: '状态'},
                {field: 'address',width: 80,title: '住址'},
                {field:'joinTime',width: 100,title:'入职时间'},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [10, 20, 50],
            limit: 10,
            page: true,
            skin: 'line',
            parseData: function(res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.data.total,
                    "data": res.data.list
                };
            },
            response: {
                statusName: 'code',
                statusCode: 0,
                msgName: 'msg',
                countName: 'count',
                dataName: 'data'
            }
        });

        // 搜索功能
        form.on('submit(data-search-btn)', function (data) {
            table.reload('currentTableId', {
                page: { curr: 1 },
                where: {
                    name: data.field.name
                }
            });
            return false;
        });
        // 重置按钮点击事件
        $('#resetSearchBtn').on('click', function () {
            table.reload('currentTableId', {
                page: { curr: 1 },
                where: {
                    name: '' // 发送空字符串作为搜索条件
                }
            });
        });

        // 工具栏事件监听
        table.on('toolbar(currentTableFilter)', function (obj) {
            switch (obj.event) {
                case 'add': // 添加用户
                    form.val('userForm', {
                        account:'',
                        userName: '',
                        gender: '男',
                        phone: '',
                        password: '',
                        address:  '',
                        status: '1'
                    });
                    loadDepartments();
                    layer.open({
                        title: '添加用户',
                        type: 1,
                        area: ['600px', '500px'],
                        content: $('#userEdit')
                    });
                    break;

                case 'assign': // 分配角色
                    var checkStatus = table.checkStatus('currentTableId');
                    if (checkStatus.data.length === 0) {
                        layer.msg('请选择要分配角色的用户');
                        return;
                    }

                    // 加载角色数据
                function loadRoles() {
                    $.getJSON('/role/queryAll', function (res) {
                        if (res.code === 0 && res.data) {
                            var options = '';
                            res.data.forEach(function (item) {
                                options += `<option value="${item.value}">${item.name}</option>`;
                            });
                            $("#roleSelect").html('<option value="">请选择角色</option>' + options);
                            form.render('select');
                        }
                    });
                }
                    // 打开分配弹窗
                    layer.open({
                        title: '分配角色',
                        type: 1,
                        area: ['600px', '450px'],
                        content: $('#roleAssign'),
                        success: function () {
                            loadRoles();
                        }
                    });
                    break;

                case 'delete': // 删除用户
                    var checkStatus = table.checkStatus('currentTableId');
                    if (checkStatus.data.length === 0) {
                        layer.msg('请选择要删除的用户');
                        return;
                    }
                    var userIds = checkStatus.data.map(item => item.userId);
                    layer.confirm('确定删除选中的用户吗？', function () {
                        $.ajax({
                            url: '/user/deleteIds',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(userIds),
                            success: function(res) {
                                if (res.code === 0) {
                                    layer.msg('删除成功');
                                    table.reload('currentTableId');
                                } else {
                                    layer.msg('删除失败: ' + res.msg);
                                }
                            }
                        });
                    });
                    break;
            }
        });

        // 新增角色分配表单提交处理
        form.on('submit(saveRoleAssign)', function (data) {
            var checkStatus = table.checkStatus('currentTableId');
            var userIds = checkStatus.data.map(item => item.userId);
            var roleId = data.field.roleId;

            // 逐个分配
            var assignedCount = 0;
            userIds.forEach(function(userId) {
                $.ajax({
                    url: '/user/addRole',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        userId: userId,
                        roleId: roleId
                    }),
                    success: function(res) {
                        if (res.code === 0) {
                            assignedCount++;
                            if (assignedCount === userIds.length) {
                                layer.msg('角色分配成功');
                                layer.closeAll();
                                table.reload('currentTableId');
                            }
                        } else {
                            layer.msg('角色分配失败: ' + res.msg);
                        }
                    }
                });
            });

            return false;
        });
        // 行工具事件监听
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                form.val('userForm', {
                    userId: data.userId,
                    account: data.account,
                    userName: data.userName,
                    gender: data.gender,
                    phone: data.phone,
                    departmentId: data.departmentId,
                    address: data.address,
                    joinTime: data.joinTime,
                    status: data.status.toString()
                });
                loadDepartments();
                layer.open({
                    title: '编辑用户',
                    type: 1,
                    area: ['600px', '500px'],
                    content: $('#userEdit')
                });
            }  else if (obj.event === 'status') {
                // 切换状态（新增状态映射逻辑）
                var newStatus = data.state === '启用' ? 0 : 1;
                $.getJSON('/user/updateUserStatus', {
                    id: data.userId,
                    status: newStatus
                }, function(res) {
                    if (res.code === 0) {
                        layer.msg('状态更新成功');
                        table.reload('currentTableId');
                    } else {
                        layer.msg('状态更新失败: ' + res.msg);
                    }
                });
            }else if (obj.event === 'viewRole') {
                var userId = data.userId;
                layer.load(2);
                $.ajax({
                    url: '/user/queryRole/' + userId,
                    type: 'GET',
                    success: function(res) {
                        layer.closeAll('loading');
                        if (res.code === 0 && res.data) {
                            // 清空旧数据
                            $('#roleInfoContent').empty();

                            // 遍历角色数据
                            res.data.forEach(function(role) {
                                var row = `                        <tr>
                            <td>${role.roleName}</td>
                            <td>${role.mark || '-'}</td>
                            <td>
                                <button class="layui-btn layui-btn-xs layui-btn-danger role-delete-btn"
                                        data-user-id="${userId}"
                                        data-role-id="${role.roleId}">
                                    删除
                                </button>
                            </td>
                        </tr>
                    `;
                                $('#roleInfoContent').append(row);
                            });

                            // 绑定删除事件（事件委托）
                            $(document).on('click', '.role-delete-btn', function() {
                                var btn = $(this);
                                var delUserId = btn.data('user-id');
                                var delRoleId = btn.data('role-id');

                                layer.confirm('确定删除该角色分配吗？', function() {
                                    $.ajax({
                                        url: '/user/deleteRole/',
                                        type: 'Post',
                                        contentType: 'application/json',
                                        data: JSON.stringify({
                                            userId: delUserId,
                                            roleId: delRoleId
                                        }),
                                        success: function(delRes) {
                                            if (delRes.code === 0) {
                                                layer.msg('角色删除成功');
                                                btn.closest('tr').remove(); // 本地删除行
                                            } else {
                                                layer.msg('删除失败: ' + delRes.msg);
                                            }
                                        }
                                    });
                                });
                            });

                            // 显示弹窗
                            layer.open({
                                title: '角色信息',
                                type: 1,
                                area: ['500px', '300px'],
                                content: $('#roleInfo')
                            });
                        } else {
                            layer.msg('获取角色信息失败: ' + (res.msg || '未知错误'));
                        }
                    },
                    error: function() {
                        layer.closeAll('loading');
                        layer.msg('网络请求失败，请检查网络连接');
                    }
                });
            }
            else if (obj.event === 'delete') {
                layer.confirm('确定删除该用户吗？', function () {
                    $.ajax({
                        url: '/user/delete/' + data.userId,
                        type: 'GET',
                        success: function(res) {
                            if (res.code === 0) {
                                layer.msg('删除成功');
                                obj.del();
                            } else {
                                layer.msg('删除失败: ' + res.msg);
                            }
                        }
                    });
                });
            }
        });



        // 保存用户
        form.on('submit(saveUser)', function (data) {
            var method = data.field.userId ? 'update' : 'add';
            $.ajax({
                url: '/user/' + method,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                success: function(res) {
                    if (res.code === 0) {
                        layer.msg('保存成功');
                        layer.closeAll();
                        table.reload('currentTableId');
                    } else {
                        layer.msg('保存失败: ' + res.msg);
                    }
                }
            });
            return false;
        });
    });
</script>
</body>
</html>
